package com.czy.seed.mvc.home.controller;

import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.base.controller.BaseController;
import com.czy.seed.mvc.home.entity.Commodity;
import com.czy.seed.mvc.home.entity.Merchant;
import com.czy.seed.mvc.home.service.CommodityService;
import com.czy.seed.mvc.home.service.MerchantService;
import com.czy.seed.mvc.sys.entity.SysUser;
import com.czy.seed.mvc.sys.mapper.SysUserMapper;
import com.czy.seed.mvc.util.FilesUpload;
import com.czy.seed.mvc.util.PrincipalUtil;
import com.czy.seed.mvc.util.Res;
import com.czy.seed.mybatis.base.QueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: liuyun
 * Created by liuyun  9:39 2017/11/23.
 */
@RestController
@RequestMapping("/home/commodity")
public class CommodityController extends BaseController<Commodity> {

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private MerchantService merchantService;

    private String url = this.getClass().getClassLoader().getResource("").getPath() + "\\" + "static" + "\\" + "lib" + "\\" + "images" + "\\";

    public static Logger logger = LoggerFactory.getLogger(CommodityController.class);
    /**
     * 查询出当前用户的商家信息
     *
     * @return
     * @Author liuyun
     *
     */
    @RequestMapping("/selectMerchant")
    public Res select() {
        QueryParams queryParams = new QueryParams(Merchant.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("userId", PrincipalUtil.getLoginUser().getId());
        List<Merchant> merchantList = merchantService.selectListByParams(queryParams);
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        pageInfo.put("merchantList", merchantList);
        return Res.ok(pageInfo);
    }

    /**
     * 根据条件查询商品信息
     * @return
     */
    @RequestMapping("/Condition")
    public  Res Conditions(String name,String brand,String model,long shopId){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        QueryParams queryParams = new QueryParams(Commodity.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andLike("commodityName", "%" + name + "%");
        criteria.andLike("brand", "%" + brand + "%");
        criteria.andLike("model", "%" + model + "%");
        criteria.andEqualTo("businessesId",shopId);
        try{
            List<Commodity> commodity = commodityService.selectListByParams(queryParams);
            pageInfo.put("commodityList",commodity);
        }catch (Exception e){
            logger.error("根据条件查询商品信息失败！");
            return Res.error("查询商品信息失败");
        }

        return Res.ok(pageInfo);

    }



    @RequestMapping("/insertCommodity")
    public String insertCommodity(MultipartHttpServletRequest request) {
        String commodity = request.getParameter("commodity");
        String urlfil = request.getParameter("url");
        try {
            Commodity Commodity = JSONObject.parseObject(commodity, Commodity.class);
            File file = new File(url + urlfil + "\\" + "commodity");
            if (!file.exists()) {
                file.mkdirs();
            }
            String URL = new FilesUpload().Upload("file", file.getCanonicalPath(), request, UUID.randomUUID().toString());
            Commodity.setMasterMap("../lib/images/" + urlfil + "/commodity/" + URL);
            BigDecimal bigDecimal = (Commodity.getCommodityMakPrc().subtract(Commodity.getCommodityTrcPrc())).divide(Commodity.getCommodityMakPrc(),2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            Commodity.setDiscounts(""+bigDecimal.intValue()+"%");
            Commodity.setCreationTime(new Date());
            Commodity.setInstall(3);
            int result = commodityService.insert(Commodity);

            logger.info("{}：添加商品表单信息成功！,商品名称为：{}", PrincipalUtil.getLoginUser().getUsername(), Commodity.getCommodityName());

        } catch (Exception e) {
            logger.error("提交商品表单信息失败！：{}", e);
            return "提交商品信息失败！";
        }

        return "提交商品信息成功！";
    }

    /*搜索功能的商品信息*/
    @RequestMapping("/shopSelect")
    public Res shopSelect(String Name, int type) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            if (type == 1) {
                QueryParams queryParams = new QueryParams(Commodity.class);
                QueryParams.Criteria criteria = queryParams.createCriteria();
                criteria.andLike("commodityName", "%" + Name + "%");
                List<Commodity> commodity = commodityService.selectListByParams(queryParams);
                pageInfo.put("commodity", commodity);
            } else if (type == 2) {
                QueryParams queryParams = new QueryParams(Merchant.class);
                QueryParams.Criteria criteria = queryParams.createCriteria();
                criteria.andLike("companyName", "%" + Name + "%");
                List<Merchant> commodity = merchantService.selectListByParams(queryParams);
                pageInfo.put("commodity", commodity);
            } else if (type == 3) {
                QueryParams queryParams = new QueryParams(Commodity.class);
                QueryParams.Criteria criteria = queryParams.createCriteria();
                criteria.andEqualTo("install", 1);
                List<Commodity> commodityList = commodityService.selectListByParams(queryParams);
                pageInfo.put("commodityList", commodityList);
            }
            logger.info("查询商品信息成功！");
        }catch(Exception e){
            logger.error("查询失败！");
        }
        return Res.ok(pageInfo);
    }

    @RequestMapping("/uploadPicture")
    public String uploadPicture(MultipartHttpServletRequest request) {
        String comm = request.getParameter("commodity");
        String name = "";
        try {
            Commodity commodity = JSONObject.parseObject(comm, Commodity.class);
            String[] str = commodity.getMasterMap().split("/");
            String urlfil = url;
            for (int i = 3; i < str.length - 1; i++) {
                if (i == (str.length - 2)) {
                    urlfil = urlfil + str[i];
                } else {
                    urlfil = urlfil + str[i] + "\\";
                }
            }
            name = str[str.length - 1];

            File file = new File(urlfil);
            //如果没有该文件信息就创建文件信息并且修改数据库中的文件保存路劲信息
            if (!file.exists()) {
                return "修改图片信息失败，未能查询出原图片保存路径！";
            }

            String URL = new FilesUpload().Upload("file", file.getCanonicalPath(), request, name.substring(0, name.indexOf('.')));
            if (!name.substring(name.indexOf('.') + 1, name.length()).equals(request.getFile("file").getOriginalFilename().substring(request.getFile("file").getOriginalFilename().indexOf('.') + 1, request.getFile("file").getOriginalFilename().length()))) {
                commodity.setMasterMap("../lib/images/" + commodity.getMasterMap().split("/")[3] + "/commodity/" + URL);
                commodityService.updateSelectiveByPrimaryKey(commodity);
            }

        } catch (Exception e) {
            logger.error("修改文件信息失败！文件名称为：{}", name, e);
            return "修改图片信息失败！";

        }
        logger.info("修改文件信息成功！文件名称为：{}", name);

        return "修改图片信息成功！";

    }

    /**
     * 修改商品信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/updateCommodity")
    public Res updateCommodity(HttpServletRequest request) {
        String commodity = request.getParameter("commodity");
        Commodity Commodity = JSONObject.parseObject(commodity, Commodity.class);
        try {
            Commodity.setUpdteTime(new Date());
            commodityService.updateSelectiveByPrimaryKey(Commodity);
            logger.info("{}：修改商品表单信息成功！,商品名称为：{}", PrincipalUtil.getLoginUser().getUsername(), Commodity.getCommodityName());

        } catch (Exception e) {
            logger.error("修改商品表单信息失败！：{}", e);
            return Res.error("修改商品信息失败！");
        }

        return Res.ok("修改商品表单信息成功");
    }
    /*非入围商家的商品上下架修改*/
    @RequestMapping("/CommodityInstall")
    public Res CommodityInstall(HttpServletRequest request){
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{
        pageInfo=commodityService.CommodityInstall_impl(request);
            logger.info("上下架成功");
        }catch(Exception e){
            logger.error("上下架失败",e);
        }
        return  Res.ok(pageInfo);
    }
    /**
     * 根据商家ID查询商品信息
     * */
    @RequestMapping("/selectCommodityByMerchant")
    public Res selectCommodityByMerchant(long id) {
        QueryParams queryParams = new QueryParams(Commodity.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("businessesId",id);
        List<Commodity> commodityList = commodityService.selectListByParams(queryParams);
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        pageInfo.put("commodityList", commodityList);
        return Res.ok(pageInfo);
    }
}
